const FormData = require("form-data");
const axios = require("axios").default.create({
  headers: {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.34 (KHTML, like Gecko) Chrome/62.0.3325.180 Safari/537.35 OPR/52.0.2871.41"
  }
});
const fs = require("fs");
const CommonAxerrHG = require("./CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const Toolbox = require("./Toolbox");
const util = require("util");
const path = require("path");
const uuid = require("uuid");

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{md:String}}>}
 */
function getMdValue() {
  return new Promise(async resolve => {
    axios.get("https://www.aigupiao.com/").then(axresp => {
      if (util.isString(axresp.data)) {
        /**@type {string} */
        let htmlstr = axresp.data;
        let matched = htmlstr.match(/"md":"([0-9a-zA-Z]*)"/);
        if (matched && matched.length == 2) {
          return resolve({
            data: {
              md: matched[1]
            },
            msg: "ok",
            ok: true
          })
        } else {
          return resolve({
            ok: false,
            msg: `can NOT find md value by RegExp`
          })
        }
      }
      throw new Error(`axresp.data is now string`)
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })
  })
}


/**
 * @returns {string} 
 * @param {String} original_name 
 */
function getGoodFilename(original_name) {
  if (original_name.endsWith(".js.map") || original_name.endsWith(".css.map")) {
    return `${uuid.v1()}.json`
  }
  return `${uuid()}${path.extname(original_name)}`;
}

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {String} file_path 
 */
function uploadImage(file_path) {
  return new Promise(async resolve => {
    let o_md = await getMdValue();
    if (!o_md.ok) {
      return resolve({
        msg: `can't get md:${o_md.msg}`
      })
    }
    let form = new FormData;
    let filestream = fs.createReadStream(file_path);

    form.append("file", filestream, {
      filename: getGoodFilename(file_path)
      // contentType: "image/png"
    });
    // form.append("fileType", "idc_license");

    axios.post(`https://www.aigupiao.com/Api/UserMsg/user_msg_upload/md/${o_md.data.md}`, form, {
      headers: {
        ...form.getHeaders(),
      },
      maxContentLength: Number.MAX_SAFE_INTEGER
    }).then(axresp => {
      if (axresp.data
        && axresp.data.name) {
        let furl = axresp.data.name;
        let index = furl.indexOf("?")
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            link: furl.substr(0, index)
          }
        })
      }
      throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })
  })
}




module.exports = {
  uploadImage
}